#!/bin/bash

TOPDIR=$PWD

function cmdHelp()
{
    echo "help                      : display help."
    echo "linux-init                : init linue source."
    echo "linux-diff                : linux source diff."
}

function cmdReturnCheck()
{
    EXEC=$1
    echo "execute command: '$EXEC'."
    $EXEC
    if [ $? -ne 0 ]; then
        echo "execute command: '$EXEC' fail."
        exit 1
    else
        echo "execute command: '$EXEC' success."
    fi
}

function cmdSourceClean()
{
    pushd $1
        find . -name "*.mod" | xargs rm -f
        find . -name "*.mod.c" | xargs rm -f
        find . -name "*.cmd" | xargs rm -f
        find . -name "*.order" | xargs rm -f
        find . -name "*.ko" | xargs rm -f
        find . -name "*.a" | xargs rm -f
        find . -name "*.o" | xargs rm -f
    popd
}

function cmdLinuxInit()
{
    if [ ! -d tmp/linux ]; then
        cmdReturnCheck "mkdir -p tmp/linux"
    fi

    pushd tmp/linux

    if [ ! -d a ]; then
        cmdReturnCheck "tar xvf $TOPDIR/tardl/linux/linux-6.10.8.tar.xz"
        cmdReturnCheck "mv linux-6.10.8 a"
    fi

    if [ ! -d b ]; then
        cmdReturnCheck "ln -s $TOPDIR/source/buildroot/buildroot-2024.08/output/build/linux-6.10.8 b"
    fi

    popd
}

function cmdLinuxDiff()
{
    if [ ! -d tmp/linux ]; then
        echo "linux-init."
        exit 1
    fi

    if [ ! -d tmp/linux/a ]; then
        echo "linux-init."
        exit 1
    fi

    if [ ! -d tmp/linux/b ]; then
        echo "linux-init."
        exit 1
    fi

    pushd tmp/linux
        cmdSourceClean "b/drivers/pwm"
        diff -Nuar a/drivers/pwm b/drivers/pwm > 0001_drivers-pwm.patch

        cmdSourceClean "b/drivers/net/wireless/realtek"
        diff -Nuar a/drivers/net/wireless/realtek b/drivers/net/wireless/realtek > 0002_drivers-net-wireless-realtek.patch
    popd
}

case $1 in

    "help")
        cmdHelp
    ;;

    "linux-init")
        cmdLinuxInit
    ;;

    "linux-diff")
        cmdLinuxDiff
    ;;

    *)
        cmdHelp
    ;;
esac
